package tool.soft

import java.io.File
import dao._
import models.Tables
import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo.PlsdaSoftT
import tool.Pojo._
import tool.{FormTool, Tool}
import tool.plot._
import tool.soft.AllSoft.SoftBT
import implicits.Implicits._
import models.Tables._
import play.api.data.FormBinding
import tool.softT.PlsdaSoftBT
import play.api.i18n.Messages
import utils.Utils
import upickle.default._

/**
 * Created by yz on 16/9/2020
 */
object PlsdaSoft extends PlsdaSoftBT with SoftBT {

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.mission.plsdaResult(missionId)
  }

  override def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val groupNum = Tool.getGroupNum(userId, data.groupFile)
    val isPairedStr = if (data.isPaired) messages("yes") else messages("no")
    val scaleMethodMap=Tool.getScaleMethodMap
    val basicJson=ujson.Obj(messages("scaleMethod") ->scaleMethodMap(data.scaleMethod))
    basicJson++{groupNum match {
      case x if x == 2 => ujson.Obj(messages("paired") -> isPairedStr)
      case x => ujson.Obj()
    }}
  }

  override def produceConfigFile(workspaceDir: File, index: Int)(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    super.produceConfigFile(workspaceDir, index)
    val data = FormTool.plsdaForm.bindFromRequest().get
    Utils.t2ConfigFile(workspaceDir,data)
    Utils.t2ConfigFile(data, Tool.getCalculateConfigJsonFile(workspaceDir))
  }

  override def getHtml(missionName: String, missionId: Option[Int])(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.soft.plsda(missionName, missionId)
  }

  override def getMission(implicit request: Request[AnyContent], matrixFileDataDao: MatrixFileDataDao, messages: Messages, formBinding: FormBinding): Tables.MissionRow = {
    val data = FormTool.plsdaForm.bindFromRequest().get
    val initInputs = List(data.file, data.groupFile)
    val argJson = getArg
    MissionRow(id = 0, missionName = s"${data.missionName}", kind = nameStr, userId = userId,
      startTime = new DateTime(), state = "preparing", arg = argJson, input = initInputs)
  }

  override def produceInputFile(workspaceDir: File)(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val userId = Tool.getUserId
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawMetaboliteFile(userId, data.file, rawDataFile)
    val groupFile = new File(workspaceDir, "group.txt")
    Tool.produceRawGroupFile(userId, data.groupFile, rawDataFile, groupFile)
  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.plsdaForm.bindFromRequest().get
  }

}

